<!--
 * @Description: 
 * @Author: DHL
 * @Date: 2022-08-24 14:58:11
 * @LastEditors: DHL
 * @LastEditTime: 2022-10-17 16:44:32
-->
<template>
  <div class="flow-designer-wrapper" v-loading="loading">
    <div class="header"> {{ title }} </div>

    <div class="main">
      <Bpmn ref="bpmnRef" @save="handleSave"></Bpmn>
    </div>
  </div>
</template>

<script lang="ts">
  export default { name: 'FlowModelDesigner' }
</script>

<script setup lang="ts">
  import { ElMessage } from 'element-plus'
  import { assign } from 'lodash-es'
  import { useRoute } from 'vue-router'
  import { apiActReModelGetById, apiActReModelSaveModelDesigner } from '/@/api/flow/actReModel'
  import { useBpmnStore } from '/@/components/bpmn/src/store/bpmn'

  const route = useRoute()

  const bpmnStore = useBpmnStore()

  const loading = ref(false)

  const title = ref('')

  const bpmnRef = ref()

  let modelData = {
    id: '',
    key: '',
    name: ''
  }

  /**
   * 查询详情
   */
  function handleSearch() {
    loading.value = true
    const id: string = route.query.id as string
    apiActReModelGetById(id)
      .then((result) => {
        if (result?.success) {
          const data = result.data
          title.value = `${data.categoryName}： ${data.name}（${data.key}）v${data.version}`
          assign(modelData, data)

          nextTick(() => {
            bpmnRef.value.handleInit(data)
          })
        } else {
          ElMessage.error(result?.message)
        }
      })
      .finally(() => {
        loading.value = false
      })
  }

  /**
   * 保存模型
   */
  function handleSave(saveParams: { key: string; name: string; xml: string }) {
    if (saveParams.key !== modelData.key) {
      ElMessage.warning(`主键值错误，正确值为【${modelData.key}】`)
      return
    }

    if (saveParams.name !== modelData.name) {
      ElMessage.warning(`名称值错误，正确值为【${modelData.name}】`)
      return
    }

    loading.value = true
    apiActReModelSaveModelDesigner({
      id: modelData.id,
      editor: saveParams.xml
    })
      .then((result) => {
        if (result?.success) {
          ElMessage.success(result.message)
        } else {
          ElMessage.error(result?.message)
        }
      })
      .finally(() => {
        loading.value = false
      })
  }

  //////////////////////////////////////////////////
  // 生命周期
  //////////////////////////////////////////////////
  onMounted(() => {
    nextTick(async () => {
      handleSearch()
    })
  })

  /**
   * 销毁组件
   */
  onBeforeUnmount(() => {
    bpmnStore.destroy()
  })
</script>

<style scoped lang="scss">
  .flow-designer-wrapper {
    height: 100%;
    .header {
      height: 40px;
      line-height: 40px;
      padding: 0px 10px;
      margin-bottom: 10px;
      background-color: #ffffff;

      font-size: 14px;
      color: #909399;
    }

    .main {
      height: calc(100% - 60px);
      padding: 5px;
      background-color: #ffffff;
    }
  }
</style>
